package com.jndv.phoneconfig.fragment;

import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.FragmentActivity;

import com.google.gson.Gson;
import com.jndv.phoneconfig.MainActivity;
import com.jndv.phoneconfig.PublicConstant;
import com.jndv.phoneconfig.R;
import com.jndv.phoneconfig.command.BatteryCommand;
import com.jndv.phoneconfig.command.HotspotStateCommand;
import com.jndv.phoneconfig.websocket.JWebSocketClient;
import com.kyleduo.switchbutton.SwitchButton;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;
import java.util.Map;

public class HotspotFragment extends BaseFragment{

    SwitchButton sb;
    EditText etName;
    EditText etPwd;
    Button btnSave;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_hotspot;
    }

    @Override
    protected void initView(View view) {
        sb=view.findViewById(R.id.sb);
        etName=view.findViewById(R.id.et_name);
        etPwd=view.findViewById(R.id.et_pwd);
        btnSave=view.findViewById(R.id.btn_save);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(TextUtils.isEmpty(etName.getText().toString())){
                    Toast.makeText(getActivity(),"热点名称不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(etPwd.getText().toString())){
                    Toast.makeText(getActivity(),"热点密码不能为空",Toast.LENGTH_SHORT).show();
                    return;
                }
                Map<String,String> innerMap=new HashMap<>();
                innerMap.put(PublicConstant.HOTSPOT_NAME,etName.getText().toString());
                innerMap.put(PublicConstant.HOTSPOT_PWD,etPwd.getText().toString());
                sendMessage(PublicConstant.CUSTOM_HOTSPOT,new Gson().toJson(innerMap));
            }
        });
        sb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Log.d("zhang","isChecked=="+isChecked);
                sendMessage(PublicConstant.AP_STATE,isChecked?"1":"0");
            }
        });

        if(isSocketConnect()){
            sendMessage(PublicConstant.CUR_HOTSPOT_STATE,"");
        }else {
            sb.setChecked(false);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCurHotspotStateEvent(HotspotStateCommand event) {
        sb.setChecked(event.isOn);
    }
}
